package net.system.sys.service;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.core.base.bean.DataTableReturnObject;
import net.core.base.bean.Page;
import net.core.base.dao.CommonDAO;
import net.core.common.StrUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CommServiceImpl implements ICommService {
	@Autowired
	private CommonDAO commonDAO;

	@Override
	public String getSeq(String string) {
		String result = "";
		String sql = "select val from seq where name='" + string + "'";
		String upd = "update seq set val=last_insert_id(val+1) where name='"
				+ string + "'";
		// 先更新序列值
		commonDAO.updateSql(upd);
		// 获取最新的值
		List<HashMap> list = commonDAO.getDataList(sql);
		if (null != list && list.size() > 0) {
			HashMap map = list.get(0);
			result = StrUtils.getNotNullStrValue(map.get("val"));

		}
		return result;
	}

	@Override
	public DataTableReturnObject getTableInfo(int pn, int iDisplayLength,
			String pid, HttpServletRequest request, String sEcho) {
		Page page = null;
		String[][] data = null;

		String errmsg = "1";// 列表组装标志 1 为正常 ；其他为组装异常。
		String zjInfo = "";
		String sql = getSQL(pid);
		List<HashMap> list = commonDAO.getPageList(sql, iDisplayLength, pn);

		if (null != list && !list.isEmpty()) {
			data = new String[list.size()][];
			for (int num = 0; num < list.size(); num++) {
				StringBuffer html = new StringBuffer("");
				HashMap map = (HashMap) list.get(num);
				String recid = StrUtils.getNotNullStrValue(map.get("rec_id"));
				//html.append("<input name='rec_Id' id='rec_Id' type='hidden' value='"
				//		+ recid + "'/>");
				Iterator iter = map.entrySet().iterator();
				while (iter.hasNext()) {
					Map.Entry entry = (Map.Entry) iter.next();
					Object key = entry.getKey();
					Object val = entry.getValue();
					if ("".equals(val)) {
						val = "-";
					}
					html.append(val);
					html.append("#@@#");
				}
				data[num] = html.toString().split("#@@#");
			}
		}

		if (page != null) {
			return new DataTableReturnObject(iDisplayLength, iDisplayLength,
					sEcho, data, errmsg, pn, zjInfo);
		} else {
			return new DataTableReturnObject(0, 0, sEcho, data, errmsg, pn,
					zjInfo);
		}
	}

	private String getSQL(String pid) {
		String sReturn = "";
		String sql = "select pi_sql from  `s_pageinfo` where rec_id='" + pid
				+ "'";
		List<HashMap> list = commonDAO.getDataList(sql);
		if (null != list && !list.isEmpty()) {
			HashMap hm = list.get(0);
			sReturn = StrUtils.getNotNullStrValue(hm.get("pi_sql"));
		}
		return sReturn;
	}

}
